/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.msu.client.event;

import io.iec.edp.caf.commons.event.StartupCompletedEvent;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.msu.api.client.ServiceRegistry;
import io.iec.edp.caf.msu.api.entity.MsuProperties;
import io.iec.edp.caf.msu.api.entity.ServiceUnitRegisterInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;

/**
 * 服务注册监听器：监听启动后事件{StartupCompletedEvent}，完成服务注册
 *
 * @author Leon Huo
 */
@Slf4j
@Order(-1024)
public class ServiceRegistryListener implements ApplicationListener<StartupCompletedEvent> {

    //服务注册
    private ServiceRegistry serviceRegistry;

    //微服务设置
    private MsuProperties configuration;

    public ServiceRegistryListener(ServiceRegistry serviceRegistry, MsuProperties configuration) {
        this.serviceRegistry = serviceRegistry;
        this.configuration = configuration;
    }

    @Override
    public void onApplicationEvent(StartupCompletedEvent event) {
        //组装实例注册信息
        //获取当前应用服务器下的所有SU信息
        ServiceUnitAwareService suAware = SpringBeanUtils.getBean(ServiceUnitAwareService.class);
        ServiceUnitRegisterInfo registerInfo = suAware.getServiceUnitRegisterInfo(this.configuration.getApplicationName(), this.configuration.getServiceName());

        log.info("ServiceCenter type [{}]", this.serviceRegistry.getClass().getName());
        //注册微服务信息
        this.serviceRegistry.register(registerInfo);

        //添加关闭进程的监听事件，停止服务时可以注销su信息
        //当前先通过@PreDestroy注解来
        //addMsuShutDownHooks(serviceUnitRegisterInfo);
    }

//    private void addMsuShutDownHooks(ServiceUnitRegisterInfo serviceUnitRegisterInfo) {
//        Thread shutdown = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                serviceRegistry.unRegister();
//            }
//        });
//        Runtime.getRuntime().addShutdownHook(shutdown);
//    }

}

